import React, { useState, useEffect, useRef } from 'react';
import { withRouter } from 'umi';
import { Collapse, Form, Icon, Tooltip, Spin, Input, Popover, Badge, Divider } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { Icon as PrivilegeIcon } from '@/pages/Setting/Privilege/components/PrivilegeIcon';
import FunctionSelector from '@/pages/Setting/Privilege/components/FunctionSelector';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import { useRequest, defaultFormatResult } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import { guid } from '@/utils/utils';
import { size } from 'lodash';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import LabelValue from './components/LabelValue';
import AuthorityData from './components/AuthorityData';
import styles from './index.less';

const operationTypeArray = {
    0: '新增',
    1: '编辑',
    2: '删除'
};

// 差异化内容
const ModifyContent = ({ title, addArr = [], delArr = [] }) => (
    <>
        <div style={{ fontSize: 14, fontWeight: 'bold', marginBottom: 10 }}>{title}：</div>
        {addArr.map(item => {
            const key = guid();
            return (
                <div key={key} className={styles.modifyContent}>
                    <Badge status="success" style={{ width: '14px' }} />
                    <p>新增：{item}</p>
                </div>
            );
        })}

        {delArr.map(item => {
            const key = guid();
            return (
                <div key={key} className={styles.modifyContent}>
                    <Badge status="error" style={{ width: '14px' }} />
                    <p>删除：{item}</p>
                </div>
            );
        })}
    </>
);

// 权限管理-模板编辑申请  ================================此页面没做提取拆分╮(╯▽╰)╭==================================

const PrivilegeTemplate = ({ dataSource, location, form, formValueMap }) => {
    const { getFieldDecorator } = form;
    const { children: list = [] } = dataSource;

    const { query } = location;
    const hiDataId = query?.hiDataId || formValueMap?.hiDataId;
    const [compareDataMap, setCompareDataMap] = useState({}); // 差异化对比映射数据源（非表格）
    const postAuthPopoverRef = useRef();
    const dutyPopoverRef = useRef();

    // 模板分组字典数据
    const [, getRoleModuleTypeText] = useDictionary('roleModuleType');

    // 获取详情
    const { data: detailData, loading: detailLoading } = useRequest(() => getPostApplyData(hiDataId), {
        ...defaultFormatResult,
        ready: !!hiDataId,
        refreshDeps: [hiDataId]
    });

    const {
        operationType,
        nameZh,
        nameEn,
        type,
        icon,
        remarkEn,
        remarkZh,
        authorityList = [],
        dataScopeSetType,
        authorityDataList = [],
        dutyGroupList = [],
        compareDataField,
        oldBusinessData,
        dutyQuantity
    } = detailData || {};
    const { updateFieldNames, seniorUpdateContent } = compareDataField || {};
    const { compareAuthority, compareDuty } = seniorUpdateContent || {};
    const { APP, PC, WEB } = compareAuthority || {}; // 功能权限差异化数据
    const { ADD: dutyAddArray, DEL: dutyDelArray } = compareDuty || {}; // 授权岗位差异化数据

    useEffect(() => {
        // 将有变更的数据进行映射
        if (updateFieldNames && updateFieldNames?.length > 0) {
            const obj = {};
            updateFieldNames.forEach(item => {
                obj[item] = oldBusinessData[item];
            });
            setCompareDataMap(obj);
        }
    }, [updateFieldNames, oldBusinessData]);

    // 功能权限差异内容
    const content = (
        <div className={styles.authModifyWrap}>
            {(size(WEB?.ADD) > 0 || size(WEB?.DEL) > 0) && (
                <>
                    <ModifyContent title="Web端" addArr={WEB?.ADD} delArr={WEB?.DEL} />
                </>
            )}
            {(size(PC?.ADD) > 0 || size(PC?.DEL) > 0) && (
                <>
                    <Divider />
                    <ModifyContent title="PC端" addArr={PC?.ADD} delArr={PC?.DEL} />
                </>
            )}
            {(size(APP?.ADD) > 0 || size(APP?.DEL) > 0) && (
                <>
                    <Divider />
                    <ModifyContent title="APP端" addArr={APP?.ADD} delArr={APP?.DEL} />
                </>
            )}
        </div>
    );

    // 岗位差异化内容
    const dutyContent = (
        <div className={styles.authModifyWrap}>
            {size(dutyAddArray) > 0 || size(dutyDelArray) > 0 ? (
                <>
                    {dutyAddArray.map(item => {
                        const key = guid();
                        return (
                            <div key={key} className={styles.modifyContent}>
                                <Badge status="success" style={{ width: '14px' }} />
                                <p>新增：{item}</p>
                            </div>
                        );
                    })}

                    {dutyDelArray.map(item => {
                        const key = guid();
                        return (
                            <div key={key} className={styles.modifyContent}>
                                <Badge status="error" style={{ width: '14px' }} />
                                <p>删除：{item}</p>
                            </div>
                        );
                    })}
                </>
            ) : (
                '无变更'
            )}
        </div>
    );

    return (
        <div className={styles.privilegeTemplateWrap}>
            <Spin spinning={detailLoading}>
                <Collapse
                    className={styles.collapsePanel}
                    bordered={false}
                    expandIconPosition="right"
                    defaultActiveKey={['1', '2', '3', '4', '5']}
                    expandIcon={panelProps => {
                        const { isActive } = panelProps;
                        return (
                            <div className={styles.collapseExpandIcon}>
                                {isActive ? '收起' : '展开'}
                                {isActive ? <Icon type="caret-up" /> : <Icon type="caret-down" />}
                            </div>
                        );
                    }}
                >
                    <Collapse.Panel header="申请原因" key="1">
                        <Form.Item label="申请类型">
                            <>{operationTypeArray[operationType]}</>
                        </Form.Item>
                        {Array.isArray(list) &&
                            list.map(item => {
                                const { label, formId, rules, extra } = item;
                                let { initialValue } = item;
                                if (formId === 'operationType') {
                                    initialValue = operationTypeArray[operationType];
                                }
                                if (formId === 'nameZh') {
                                    initialValue = nameZh;
                                }
                                return (
                                    <Form.Item
                                        label={label}
                                        key={formId}
                                        extra={extra}
                                        style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                                    >
                                        {getFieldDecorator(formId, {
                                            initialValue,
                                            rules
                                        })(<AutoRenderComponent form={form} config={item} />)}
                                    </Form.Item>
                                );
                            })}
                        <Form.Item style={{ display: 'none' }}>
                            {form.getFieldDecorator('hiDataId', {
                                initialValue: hiDataId
                            })(<Input />)}
                        </Form.Item>
                    </Collapse.Panel>
                    <Collapse.Panel header="基础信息" key="2">
                        <LabelValue
                            labelAlignItems="center"
                            label="模板名称(中文)"
                            value={
                                <Difference className={styles.differenceText} tip={compareDataMap?.nameZh}>
                                    {nameZh}
                                </Difference>
                            }
                        />
                        <LabelValue
                            labelAlignItems="center"
                            label="模板名称(英文)"
                            value={
                                <Difference className={styles.differenceText} tip={compareDataMap?.nameEn}>
                                    {nameEn}
                                </Difference>
                            }
                        />
                        <LabelValue
                            labelAlignItems="center"
                            label="模板分组"
                            value={
                                <Difference
                                    className={styles.differenceText}
                                    tip={getRoleModuleTypeText(compareDataMap?.type)}
                                >
                                    <div>{getRoleModuleTypeText(type)}</div>
                                </Difference>
                            }
                        />
                        <LabelValue
                            labelAlignItems="center"
                            label="模版图标"
                            value={
                                <Difference
                                    tipCover={
                                        compareDataMap?.icon ? (
                                            <div>
                                                旧图标：
                                                <PrivilegeIcon size={25} icon={compareDataMap?.icon} />
                                            </div>
                                        ) : (
                                            undefined
                                        )
                                    }
                                >
                                    <PrivilegeIcon icon={icon} />
                                </Difference>
                            }
                        />
                        <LabelValue
                            labelAlignItems="center"
                            label="模板简介(中文)"
                            value={
                                <Difference className={styles.differenceText} tip={compareDataMap?.remarkZh}>
                                    {remarkZh}
                                </Difference>
                            }
                        />
                        <LabelValue
                            labelAlignItems="center"
                            label="模板简介(英文)"
                            value={
                                <Difference className={styles.differenceText} tip={compareDataMap?.remarkEn}>
                                    {remarkEn}
                                </Difference>
                            }
                        />
                    </Collapse.Panel>
                    <Collapse.Panel header="功能权限" key="3">
                        {operationType === 1 && (
                            <div className={styles.compareBarWrap}>
                                <span className={styles.green}>
                                    新增：WEB端（{size(WEB?.ADD)}） &nbsp; PC端（{size(PC?.ADD)}）&nbsp; APP端（
                                    {size(APP?.ADD)}）
                                </span>
                                <span className={styles.red}>
                                    删除: WEB端（{size(WEB?.DEL)}） &nbsp; PC端（{size(PC?.DEL)}） &nbsp; APP端（
                                    {size(APP?.DEL)}）
                                </span>
                                <Popover
                                    content={content}
                                    title="变更内容"
                                    placement="rightBottom"
                                    arrowPointAtCenter
                                    trigger="click"
                                    align={{ targetOffset: ['0%', 0] }}
                                    overlayClassName={styles.postAuthPopover}
                                    getPopupContainer={() => postAuthPopoverRef.current}
                                >
                                    <span className={styles.showCompareBtn} ref={postAuthPopoverRef}>
                                        查看功能权限变更记录
                                    </span>
                                </Popover>
                            </div>
                        )}

                        <FunctionSelector disabled value={authorityList} isShow />
                    </Collapse.Panel>
                    <Collapse.Panel header="数据权限" key="4">
                        <AuthorityData
                            dataScopeSetType={dataScopeSetType}
                            authorityDataList={authorityDataList}
                            compareDataMap={compareDataMap}
                        />
                    </Collapse.Panel>
                    <Collapse.Panel header="授权岗位" key="5">
                        {operationType === 1 && (
                            <div className={styles.compareBarWrap}>
                                <span className={styles.green}>新增：{size(dutyAddArray)}</span>
                                <span className={styles.red}>删除: {size(dutyDelArray)}</span>
                                <Popover
                                    content={dutyContent}
                                    title="变更内容"
                                    placement="rightBottom"
                                    arrowPointAtCenter
                                    trigger="click"
                                    align={{ targetOffset: ['0%', 0] }}
                                    overlayClassName={styles.postAuthPopover}
                                    getPopupContainer={() => dutyPopoverRef.current}
                                >
                                    <span className={styles.showCompareBtn} ref={dutyPopoverRef}>
                                        查看功能权限变更记录
                                    </span>
                                </Popover>
                            </div>
                        )}
                        <LabelValue
                            label="已授权岗位"
                            labelAlignItems="center"
                            labelInline
                            labelStyles={{ marginLeft: 16 }}
                            grid={false}
                            value={
                                <Difference className={styles.differenceText} tip={compareDataMap?.dutyQuantity}>
                                    {dutyQuantity}
                                </Difference>
                            }
                        />
                        {size(dutyGroupList) > 0 && (
                            <div className={styles.postTabpaneBox}>
                                {dutyGroupList.map(item => (
                                    <div className={styles.list} key={item?.orgCode}>
                                        <div className={styles.orgName}>{item?.orgName}</div>
                                        <div className={styles.orgList}>
                                            {item?.dutyNameList.map(subItem => {
                                                const key = guid();
                                                return (
                                                    <Tooltip title={item?.orgFullName} key={key}>
                                                        <span>{subItem}</span>
                                                    </Tooltip>
                                                );
                                            })}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </Collapse.Panel>
                </Collapse>
            </Spin>
        </div>
    );
};

export default withRouter(PrivilegeTemplate);
